﻿using Koala.Pro.CodeGenerator.UI.Common;

namespace Koala.Pro.CodeGenerator.UI.DatabaseModel
{
    public class DatabaseConfig
    {
        private const string XmlPath = "DatabaseSetting.xml";

        public static DatabaseSetting[] ReadSettings()
        {
            return XmlUtils.LoadObjectFromXml("DatabaseSetting.xml", typeof(DatabaseSetting[])) as DatabaseSetting[];
        }

        public static bool Save(DatabaseSetting[] settings)
        {
            bool result = false;
            if (settings != null)
            {
                XmlUtils.SaveObjectToXml("DatabaseSetting.xml", settings);
                result = true;
            }
            return result;
        }

        public static DatabaseSetting[] Add(DatabaseSetting setting)
        {
            DatabaseSetting[] array = ReadSettings();
            if (setting != null)
            {
                List<DatabaseSetting> list = new List<DatabaseSetting>(array);
                list.Add(setting);
                array = list.ToArray();
                XmlUtils.SaveObjectToXml("DatabaseSetting.xml", array);
            }
            return array;
        }

        public static DatabaseSetting[] Modify(DatabaseSetting setting)
        {
            DatabaseSetting[] array = ReadSettings();
            if (array != null)
            {
                List<DatabaseSetting> list = new List<DatabaseSetting>(array);
                DatabaseSetting[] array2 = array;
                foreach (DatabaseSetting databaseSetting in array2)
                {
                    if (setting.DatabaseType.Equals(databaseSetting.DatabaseType, StringComparison.OrdinalIgnoreCase))
                    {
                        databaseSetting.AssemblyName = setting.AssemblyName;
                        databaseSetting.AssemblyType = setting.AssemblyType;
                        databaseSetting.ConnectString = setting.ConnectString;
                    }
                }
                array = list.ToArray();
                XmlUtils.SaveObjectToXml("DatabaseSetting.xml", array);
            }
            return array;
        }

        public static DatabaseSetting[] Delete(string databaseType)
        {
            DatabaseSetting[] array = ReadSettings();
            if (array != null)
            {
                List<DatabaseSetting> list = new List<DatabaseSetting>(array);
                DatabaseSetting[] array2 = array;
                foreach (DatabaseSetting databaseSetting in array2)
                {
                    if (databaseSetting.DatabaseType.ToLower() == databaseType.ToLower())
                    {
                        list.Remove(databaseSetting);
                    }
                }
                array = list.ToArray();
                XmlUtils.SaveObjectToXml("DatabaseSetting.xml", array);
            }
            return array;
        }
    }
}
